<template>
  <Title>
    <template v-slot:center>用户注册</template>
  </Title>
  <div id="register">
    <h1>图书商城</h1>
    <van-form @submit="onSubmit">
      <van-field
          v-model="name"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
          v-model="password_confirmation"
          type="password"
          name="确认密码"
          label="确认密码"
          placeholder="确认密码"
          :rules="[{ required: true, message: '请填写一致密码' }]"
      />
      <van-field
          v-model="email"
          name="邮箱"
          label="邮箱"
          placeholder="请输入正确邮箱格式"
          :rules="[{ required: true, message: '请填写正确格式邮箱' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit" color="#42b983">
          提交
        </van-button>
      </div>
    </van-form>
    <div class="link-login" @click="$router.push({path:'/login'})">已有账号，立即登录</div>
  </div>
</template>

<script>
import Title from "../../components/common/title/Title";
import {reactive, ref, toRefs} from "vue";
import {register} from "../../network/user";
import {Notify,Toast} from 'vant'
import {useRouter} from 'vue-router'
export default {
  components:{Title},
  setup(){
    const router=useRouter()
    const userinfo=reactive({
      name:'',
      password:'',
      password_confirmation:'',
      email:''
    })
    const onSubmit=()=>{
      if(userinfo.password!=userinfo.password_confirmation){
          Notify('两次密码不一致')
          userinfo.name='';
          userinfo.password_confirmation='';
      }else{
        register(userinfo).then(res=>{
            if(res.status=='201'){
              Toast.success('注册成功')
              setTimeout(()=>{
                router.push({path:'/login'})
              },1000)
            }
        })
      }
    }
    return{...toRefs(userinfo),onSubmit}
  }
}
</script>

<style scoped lang="scss">
#register{
  padding: 45px 0 50px;
  h1{
    text-align: center;
  }
  .link-login{
    text-align: center;
  }
}
</style>